<?php

	// +----------------------------------------------------------------------
	// | 商品内容模型
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\event\store;

	use app\common\event\Base;
	use app\model\ucenter\User as UserModel;
	use app\model\store\GoodCard as GoodCardModel;
	use app\model\store\Good as GoodModel;
	use app\model\store\Store as StoreModel;
	use app\event\ucenter\User as UserEvent;
	use think\Exception;
	use think\facade\Url;
	use wechat\official_account\Template as TemplateOfficial;

	class GoodCard extends Base
	{

		/**
		 * 卖家信息
		 * @var StoreModel
		 */
		private $store;
		/**
		 * 会员信息
		 * @var UserModel
		 */
		private $user;
		/**
		 * 商品信息
		 * @var GoodModel
		 */
		private $good;

		/**
		 * 新增卡密
		 * @param array $param
		 * @param StoreModel $store
		 * @param UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function add($param, $store,$user)
		{
			try {
				// 验证权限
				// 数量控制
				// 商品验证
				$this->good = $store->goods()->where('id', $param['good_id'])->find();
				if (!$this->good) {
					throw new Exception('商品不存在');
				}
				$addAll = [];
				if (0 == $param['type']) {
					$contents = explode("\n", trim($param['content']));
					if (count($contents)) {
						foreach ($contents as $key => $content) {
							$content = explode($param['format'], trim($content));
							if (count($content) == 2) {
								$add['card_sn'] = $content[0];
								$add['content'] = $content[1];
							} elseif (count($content) == 1) {
								$add['card_sn'] = uniqid();
								$add['content'] = $content[0];
							} else {
								continue;
							}
							$add['title'] = $this->good['title'];
							$add['store_id'] = $store['id'];
							$add['user_id'] = $user['id'];
							if (!$this->good->cards()->where('card_sn', $add['card_sn'])->find()) {
								$addAll[] = $add;
							}
						}
					}

				} elseif (1 == $param['type']) {
					for ($x = 0; $x < $param['count']; $x++) {
						$add = [];
						$add['card_sn'] = uniqid();
						$add['content'] = substr(md5(uniqid()), 12, 18);
						$add['title'] = $this->good['title'];
						$add['store_id'] = $store['id'];
						$add['user_id'] = $user['id'];
						$addAll[] = $add;
					}
				}
				if (count($addAll)) {
					$result = $this->good->cards()->saveAll($addAll);
					// 更新库存
					$this->good['stock'] = $this->good->cards()->where('status', 1)->count('*');
					$this->good->save();
					if (1 == $this->good['is_open_agent']) {
						// 开放代理，同步库存
						if ($this->good->agentGoods()->find()) {
							$this->good->agentGoods()->where('status', '>', -2)->update(['stock' => $this->good['stock']]);
						}
					}
				} else {
					$result = [];
				}
				if (count($result) == 0)
				{
					throw new Exception( '新增' . count($result) . '张卡密');
				}
				$data['data'] = '新增' . count($result) . '张卡密';
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 更新商品内容
		 * @param array $param
		 * @param UserModel $user
		 * @return mixed
		 */
		public function update($param, $user = null)
		{
			try {
				$store = $this->request->store;
				$card = GoodCardModel::where('store_id',$store['id'])->where('id',$param['id'])->find();
				if (!$card)
				{
					throw new Exception('未查询到卡密');
				}
				// 修改
				$card = GoodCardModel::get($param['id']);
				$card['card_sn'] = $param['card_sn'];
				$card['content'] = $param['content'];
				if (!$card->save()) {
					throw new Exception('修改异常');
				}
				$data['message'] = '修改成功';
				$data['data'] = $card;
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}

			return $data;
		}

		/**
		 * 发送更新商品队列
		 * @param $data
		 * @throws \think\Exception
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public static function taskTemplateGoodUpdateFocusJob($data)
		{
			$users = UserModel::has('oauths', ['channel' => 'wechat', 'status' => 1])->where('User.id', 'in', $user_ids)->select();
			// 发送;
			$event = new TemplateOfficial();
			$WechatTemplate = WechatTemplateModel::where('wechat_no', 'OPENTM411013653')->where('status', 1)->find();
			foreach ($users as $u) {
				$wechat = $u->oauths()->where('channel', 'wechat')->where('status', 1)->find();
				if ($wechat) {
					$param = [
						'first' => ['value' => '尊敬的用户【' . $u['nickname'] . '】，您关注的商品更新了章节。', 'color' => '#000000'],
						'keyword1' => ['value' => $good['title'], 'color' => '#000000'],
						'keyword2' => ['value' => $good['catalog_now'] . '/' . $good['catalog'], 'color' => '#000000'],
						'keyword3' => ['value' => time_format(), 'color' => '#000000'],
						'remark' => ['value' => '感谢您的关注，如果不需要此通知，可以在我的详情里面取消通知！', 'color' => '#000000'],
					];
					$event->send($wechat['open_id'],
						$WechatTemplate['template_id'],
						Url::build('card/Good/detail', ['id' => $good['id']], true, true), $param);
				}
			}
		}
	}
